<template>
  <div class="main">
    <div class="bg">
      <img v-lazy="publicUrl(`/images/loginBg.jpg`)" />
      <span class="title">找工厂，就上云裁</span>
      <div class="login-div" v-show="!showStore && loginMode === 'pass'">
        <div class="right-qrcode thumb" title="扫码登陆" @click="()=>modeChange('sweep')" v-show="loginMode === 'pass'">
          <img v-lazy="publicUrl(`/images/qrcode.png`)" />
        </div>
     
        <div class="login-div-top">
          <div class="font thumb" @click="()=>activitName = 1">
            密码登录
            <div class="sel" v-show="activitName === 1"></div>
          </div>
          <div class="font thumb" @click="()=>activitName = 2">
            短信登录
            <div class="sel" v-show="activitName === 2"></div>
          </div>
        </div>

        <form>
          <div class="input input-first" v-show="activitName === 1">
            <div class="left">
              <div class="icon">
                <img v-lazy="publicUrl(`/images/login-user.png`)" />
              </div>
            </div>
            <div class="right">
              <input
                v-model="pass.username"
                autocomplete="“off”"
                placeholder="请输入手机号码17325764719"
                :onBlur="validateBlur"
              />
            </div>
          </div>

          <div class="input" v-show="activitName === 1">
            <div class="left">
              <div class="icon">
                <img v-lazy="publicUrl(`/images/login-lock.png`)" />
              </div>
            </div>
            <div class="right">
              <input
                v-model="pass.password"
                autocomplete="“off”"
                :type="see ? `input` : `password`"
                placeholder="请输入密码123456"
                :onBlur="validateBlur"
              />
            </div>
            <div class="eyes thumb" @click="()=>see = !see">
              <img
                :src="
                  publicUrl(
                    see
                      ? `/images/login-eyes.png`
                      : `/images/login-eyes-close.png`
                  )
                "
              />
            </div>
          </div>

          <div class="input input-first" v-show="activitName === 2">
            <div class="left">
              <div class="icon">
                <img v-lazy="publicUrl(`/images/login-phone.png`)" />
              </div>
            </div>
            <div class="right">
              <input
                autocomplete="“off”"
                placeholder="请输入手机号码"
                name="phone"
                v-model="sms.phone"
                :onBlur="validateBlur"
              />
            </div>
          </div>

          <div class="input" v-show="activitName === 2">
            <div class="left">
              <div class="icon">
                <img v-lazy="publicUrl(`/images/login-code.png`)" />
              </div>
            </div>
            <div class="right">
              <input
                autocomplete="off"
                placeholder="请输入验证码"
                v-model="sms.captcha"
                :onBlur="validateBlur"
              />
            </div>
            <Button
              v-show="cooling === 0"
              :background="`white`"
              class="thumb get-code"
              v-debounce="getCode"
              :color="`#3644BF`"
              :size="`.0729rem`"
              :loading="loading.getCode"
              >获取验证码</Button
            >
            <Button
              v-show="cooling > 0"
              :background="`white`"
              class="thumb get-code"
              :color="`#3644BF`"
              :size="`.0729rem`"
              >{{ cooling }}&nbsp;重新获取</Button
            >
          </div>
          <div class="errorMsg">
            {{ activitName === 1 ? errorMsgPass : errorMsgSms }}&nbsp;
          </div>
        </form>





        <div class="small-sel">
          <span class="thumb">忘记密码</span>
          <span class="thumb">忘记用户名</span>
          <span class="thumb" @click="()=>go(`/register`)">免费注册</span>
        </div>




        <Button
          :background="`#232481`"
          v-debounce="login"
          :loading="loading.login"
          class="login-btn thumb"
          :color="`white`"
          :size="`.0833rem`"
          >登录</Button
        >
      </div>


      <div class="login-div" v-show="!showStore && loginMode === 'sweep'">
        <div class="right-icon thumb" title="短信密码登陆" @click="()=>modeChange('pass')"  v-show="loginMode === 'sweep'">
          <img v-lazy="publicUrl(`/images/pc-login.png`)" />
        </div>
     
        <div class="left-title">扫码登录</div>

        <div class="qrcode">
                <img v-lazy="publicUrl(`/images/qrcode.png`)" />
          </div>

        <div class="sweep-text">
            <img v-lazy="publicUrl(`/images/pc-sweep.png`)" />  <span>手机扫一扫登录</span>
        </div>

       
        



       
      </div>

      <div class="store-div" v-show="showStore">
        <div class="store-list">
          <div class="store-container">
            <div class="store-title">请选择登录门店</div>
            <div v-show="storeList.length > 0">
              <div
                class="store-container-part"
                v-for="(item, index) in storeList"
                :key="index"
              >
                <div class="logo"><img v-lazy="publicUrl(item.avatar)" /></div>
                <div class="part-center overOne">
                  <div class="username overOne">账号: {{ item.username }}</div>
                  <div class="id overOne">ID: {{ item.user_id }}</div>
                </div>
                <div class="login-in thumb" @click="()=>loginIn(item)">
                  登录进入
                </div>
              </div>
            </div>
            <!-- <div class="no-store" v-show="storeList.length === 0">
              暂无登录的门店
            </div> -->
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts" name="">
import { publicUrl, validateRule } from "@/utils/util";
import { ref, reactive } from "vue";
import { login as getLoginCode } from "@/api/modules/getCode";
import Button from "@/components/Button/index.vue";
import { useForm } from "vee-validate";
import { ResultEnum } from "@/enums/httpEnum";
import { GlobalStore } from "@/stores/index";

import { pass as passApi, sms as smsApi } from "@/api/modules/login";

import * as yup from "yup";

import { useRouter } from "vue-router";
const store = GlobalStore();

const router = useRouter();

const see = ref<boolean>(false);

const activitName = ref<1 | 2>(1);
const errorMsgPass = ref<string>("");
const errorMsgSms = ref<string>("");

const showStore = ref<boolean>(false);

interface User {
  user_id: string;
  username: string;
  avatar: string;
  token: string;
  order_num: number;
  amount: number;
  toBePaidNum: number; //待付款数量
  pendingOrderNum: number; //待接单数量
  inProductionNum: number; //生产中数量
  goodsNum: number; //待发货
}

const storeList = ref<Array<User>>([
  {
    username: "中山天凯网络",
    user_id: "202301017565468451",
    avatar: "/images/storeImg.png",
    token: "123123123",
    order_num: 3000,
    amount: 1888888,
    toBePaidNum: 10, //待付款数量
    pendingOrderNum: 20, //待接单数量
    inProductionNum: 30, //生产中数量
    goodsNum: 40, //待发货
  },
  {
    username: "中山天凯网络",
    user_id: "202301017565468451",
    avatar: "/images/storeImg.png",
    token: "123123123",
    order_num: 3000,
    amount: 1888888,
    toBePaidNum: 10, //待付款数量
    pendingOrderNum: 20, //待接单数量
    inProductionNum: 30, //生产中数量
    goodsNum: 40, //待发货
  },
  {
    username: "中山天凯网络",
    user_id: "202301017565468451",
    avatar: "/images/storeImg.png",
    token: "123123123",
    order_num: 3000,
    amount: 1888888,
    toBePaidNum: 10, //待付款数量
    pendingOrderNum: 20, //待接单数量
    inProductionNum: 30, //生产中数量
    goodsNum: 40, //待发货
  },
  {
    username: "中山天凯网络",
    user_id: "202301017565468451",
    avatar: "/images/storeImg.png",
    token: "123123123",
    order_num: 3000,
    amount: 1888888,
    toBePaidNum: 10, //待付款数量
    pendingOrderNum: 20, //待接单数量
    inProductionNum: 30, //生产中数量
    goodsNum: 40, //待发货
  },
]);

const loading = reactive<{
  getCode: boolean;
  login: boolean;
}>({
  getCode: false,
  login: false,
});

interface PassForm {
  username: string;
  password: string;
}
interface SmsForm {
  phone: string;
  captcha: string;
}

const loginMode = ref<'pass'|'sweep'>('pass');


// Yup.string()
// .required()
// .matches(/^[0-9]+$/, "Must be only digits")
// .min(5, 'Must be exactly 5 digits')
// .max(5, 'Must be exactly 5 digits')
// const values = reactive<Form>({
//       username: '',
//       password: '',
//       phone: '',
//       captcha: '',
// });

const { validate: passValidate, values: pass } = useForm<PassForm>({
  initialValues: {
    username: "",
    password: "",
  },
  validationSchema: {
    username: yup
      .string()
      .required("手机号不为空")
      .matches(validateRule("phone"), "必须为手机格式"),
    password: yup
      .string()
      .required("密码不为空")
      .min(5, "密码不少于5个字符")
      .max(20, "密码不必须小于于20个字符"),
  },
});

const go = (path: string) => router.push(path);

const { validate: smsValidate, values: sms } = useForm<SmsForm>({
  initialValues: {
    phone: "",
    captcha: "",
  },
  validationSchema: {
    phone: yup
      .string()
      .required("手机号码不为空")
      .matches(validateRule("phone"), "必须为手机格式"),
    captcha: yup
      .string()
      .required("验证码不为空")
      .length(5, "验证码必须为5位数"),
  },
});

const cooling = ref<number>(0);

const loginIn = (item: User) => {
  store.setUserInfo(
    {
      username: item.username,
      user_id: item.user_id,
      avatar: item.avatar,
      order_num: item.order_num,
      amount: item.amount,
      toBePaidNum:item.toBePaidNum,   //待付款数量
			pendingOrderNum:item.pendingOrderNum,   //待接单数量
			inProductionNum:item.inProductionNum,   //生产中数量
			goodsNum:item.goodsNum,   //待发货
    },
    item.token
  );
  router.push("/home");
};

const reduceFunc = () => {
  setTimeout(() => {
    cooling.value--;
    if (cooling.value >= 1) reduceFunc();
  }, 1000);
};

/**
 * 获取验证码
 */
const getCode = async () => {
  const { errors } = await smsValidate();
  if (errors.phone) return (errorMsgSms.value = errors.phone);
  loading.getCode = true;
  await getLoginCode();
  cooling.value = 60;
  reduceFunc();
  loading.getCode = false;
};

const validateBlur = async () => {
  const { valid, errors } =
    activitName.value === 1 ? await passValidate() : await smsValidate();
  let message: string =
    valid === false
      ? ((errors as { [key: string]: string })[
          Object.keys(errors)[0]
        ] as string)
      : "";
  activitName.value === 1
    ? (errorMsgPass.value = message)
    : (errorMsgSms.value = message);
  return valid;
};

const modeChange = (mode:'pass'|'sweep')=>{
  // alert();
  loginMode.value = mode
}

/**
 * 获取验证码
 */
const login = async () => {
  let check = await validateBlur();
  if (check) {
    loading.login = true;
    let res: any =
      activitName.value === 1 ? await passApi(pass) : await smsApi(sms);
    if (res.code === ResultEnum.SUCCESS) {
      showStore.value = true;
    } else {
      activitName.value === 1
        ? (errorMsgPass.value = res.msg)
        : (errorMsgSms.value = res.msg);
    }
  }
  loading.login = false;
};
</script>
<style scoped lang="scss">
@media screen and (min-width: $pc-min-width) {
  @import "./pc.scss";
}
</style>
